package com.education.wisdom.controller.app;

import com.education.common.config.BusinessException;
import com.education.common.config.CommonErrorCode;
import com.education.common.core.BaseController;
import com.education.common.core.TableDataInfo;
import com.education.common.pojo.AjaxResult;
import com.education.common.utils.ApiReturnObject;
import com.education.common.utils.LogUtil;
import com.education.common.utils.UUIDUtils;
import com.education.wisdom.pojo.*;
import com.education.wisdom.service.*;
import com.education.wisdom.vo.ResourcesVo;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.math.BigDecimal;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 视频资源 信息操作处理
 *
 * @author ruoyi
 * @date 2018-11-07
 */
@Controller
@RequestMapping(value = "/AppResources")
@CrossOrigin(allowCredentials = "true")
@Api(tags = {"视频资源模"})
@Slf4j
public class AppResourcesController extends BaseController {

    @Autowired
    private IResourcesService resourcesService;

    @Autowired
    private ICatalogService catalogService;

    @Autowired
    private IResourcesPayService iResourcesPayService;

    @Autowired
    private IUserAccountService userAccountService;

    @Autowired
    private ICurrencyRecordService currencyRecordService;

    @Autowired
    private IMerchantOrderService merchantOrderService;

    @Autowired
    private ICatalogUserService iCatalogUserService;

    /**
     * 教学云课堂--实战视频和实战照片
     *
     * @param catalogId 课程id
     * @param type      类型 :  4 视频 5 图片
     * @return
     */
    @GetMapping("/selectByViedo")
    @ResponseBody
    public ApiReturnObject selectByViedo(Integer catalogId, Integer type) {
        if (catalogId == null || type == null){
            throw new BusinessException(CommonErrorCode.E_200101);
        }
        List<Resources> resources = resourcesService.selectResourcesByCatalogIdAndType(catalogId, type);
        return new ApiReturnObject("200", "success", resources);
    }

    /**
     * 教学云课堂--教学资料
     *
     * @param catalogId 课程id
     * @return
     */
    @GetMapping("/selectByData")
    @ResponseBody
    public ApiReturnObject selectByData(Integer catalogId) {
        if (catalogId == null){
            throw new BusinessException(CommonErrorCode.E_200101);
        }
        Map<String,Object> map = new HashMap<>();

        List<Resources> jxkj = resourcesService.selectResourcesByCatalogIdAndType(catalogId,1);
        map.put("jxkj",jxkj);

        List<Resources> jswd = resourcesService.selectResourcesByCatalogIdAndType(catalogId,3);
        map.put("jswd",jswd);
        return new ApiReturnObject("200", "success", map);
    }

    /**
     * 查询视频资源信息
     */
    @RequestMapping("/info")
    @ResponseBody
    @ApiOperation("视频资源路径")
    @ApiImplicitParams({@ApiImplicitParam(name = "rCatalogid", value = "课程ID", dataType = "Integer"),
            @ApiImplicitParam(name = "userId", value = "用户id", dataType = "String")})

    public void info(Integer rCatalogid, HttpServletResponse response, HttpServletRequest request, String userId) throws Exception {
       /* log.info(LogUtil.LogInfo("视频资源路径",new Date()));
		SysAppLogin user = (SysAppLogin)request.getSession().getAttribute("user");
		if (user != null){
			//Resources resources = resourcesService.selectUrl(rCatalogid);
			ResourcesVo resources=resourcesService.selectResources(rCatalogid);
			if (resources.getFreeFlag()!="1"){
				Catalog catalog = new Catalog();
				Integer clickNum = (catalogService.cNumber(rCatalogid).getCatalogLearningNum())+1;
				catalog.setCatalogLearningNum(clickNum);
				catalog.setCatalogId(rCatalogid);
				*//** 点击量增加 *//*
				catalogService.updateCataLog(catalog);
				writeJSON(resources,response,"200","success");
			}else{
				writeJSON("该课程为付费课程",response,"201","error");
			}
		}else {
			writeJSON("请前往登陆",response,"201","false");
		}*/
        //Resources resources = resourcesService.selectUrl(rCatalogid);
        /*if(userId!=null){*/
        ResourcesVo resources = resourcesService.selectResources(rCatalogid);
        if (!resources.getFreeFlag().equals("1")) {
            Catalog catalog = new Catalog();
            Integer clickNum = (catalogService.classInfo(rCatalogid).getCatalogLearningNum()) + 1;
            catalog.setCatalogLearningNum(clickNum);
            catalog.setCatalogId(rCatalogid);
            //点击量增加
            log.info(LogUtil.LogInfo("点击量增加", new Date()));
            catalogService.updateCataLog(catalog);
            // 判断是否重复学习
            if (iCatalogUserService.selectByUserId(rCatalogid) == null) {
                //加入我的学习课程
                CatalogUser catalogUser = new CatalogUser();
                catalogUser.setCatalogId(resources.getrCatalogid());
                catalogUser.setUserId(userId);
                catalogUser.setCreateTime(new Date());
                log.info(LogUtil.LogInfo("用户开始学习课程", new Date()));
                iCatalogUserService.insertCatalogUser(catalogUser);
                writeJSON(resources, response, "200", "学习课程成功");
            } else {
                writeJSON(resources, response, "200", "该课程正在学习");
            }
//				writeJSON(resources,response,"200","success");
        } else {
            writeJSON("该课程为付费课程", response, "201", "error");
        }
		/*}else {
			writeJSON("请进行登录",response,"201","error");
		}*/
    }

    /**
     * 新增保存视频资源
     */
    @PostMapping("/add")
    @ResponseBody
    public AjaxResult addSave(Resources resources) {
        String rUrl = resources.getrUrl();
        String[] rUrls = rUrl.split(",");
        for (String rurl : rUrls) {
            if ("".equals(rurl) == false && rurl != null) {
                resources.setrUrl(rurl);
                resourcesService.insertResources(resources);
            }
        }
        return toAjax(1);
    }

    /**
     * 查询资源列表
     */
    @PostMapping("/lists")
    @ResponseBody
    public TableDataInfo lists(Resources resources) {
        startPage();
        List<Resources> list = resourcesService.selectResourcesListBytype(resources);
        return getDataTable(list);
    }

    /**
     * 查询我付费的视频资源列表
     */
    @ApiOperation("根据用户ID获取付费视频资源列表")
    @GetMapping("/findPayByUserId")
    @ApiImplicitParam(name = "userId", value = "用户ID", dataType = "String")
    @ResponseBody
    public void findPayByUserId(HttpServletResponse response, String userId, Integer pageNo, Integer pageSize) throws IOException {
        PageHelper.startPage(pageNo, pageSize);
        log.info(LogUtil.LogInfo("查询视频资源记录", new Date()));
        List<ResourcesVo> list = resourcesService.selectResourcesVoList(userId);
        PageInfo<ResourcesVo> page = new PageInfo<>(list);
        writeJSON(page, response, "200", "success");
    }

    /**
     * 根据用户ID查询视频集合
     */
    @ApiOperation("根据用户ID查询视频集合")
    @GetMapping("/findByUserId")
    @ApiImplicitParam(name = "userId", value = "用户ID", dataType = "String")
    @ResponseBody
    public void findByUserId(HttpServletResponse response, String userId, Integer pageNo, Integer pageSize) throws IOException {
        PageHelper.startPage(pageNo, pageSize);
        log.info(LogUtil.LogInfo("查询视频资源记录", new Date()));
        List<ResourcesVo> list = resourcesService.selectResourcesVoLists();
        for (int i = 0; i < list.size(); i++) {
            String freeFlag = list.get(i).getFreeFlag();
            if ("1".equals(freeFlag)) {
                String resourcesId = list.get(i).getrNumber();//视频资源ID
                Map<String, Object> map = new HashMap<String, Object>();
                map.put("userId", userId);
                map.put("resourcesId", resourcesId);
                ResourcesPay pay = iResourcesPayService.selectResourcesPayByMap(map);
                String delFlag = pay.getDelFlag();//(0：正常，1：删除)
                String jrFreeFlagType = pay.getJrFreeFlagType();//1现金 2币
                Date effectiveTime = pay.getEffectiveTime();//有效期
                Date nowTime = new Date();
                if ("0".equals(delFlag)) {
                    if (effectiveTime.before(nowTime)) {//没有过期
                        list.get(i).setJrFreeFlagType(jrFreeFlagType);
                        list.get(i).setJrFreeFlagType(jrFreeFlagType);
                        list.get(i).setEffectiveTime(effectiveTime);
                    }
                }
            }
        }
        PageInfo<ResourcesVo> page = new PageInfo<ResourcesVo>(list);
        writeJSON(page, response, "200", "success");
    }


    /**
     * 确认用勋章币购买课程资源订单
     */
    @ApiOperation("确认用勋章币购买课程资源订单")
    @GetMapping("/payByUserId")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "userId", value = "用户ID", dataType = "string"),
            @ApiImplicitParam(name = "orderId", value = "订单id", dataType = "string")})
    @ResponseBody
    public void payByUserId(HttpServletResponse response, String userId, String orderId) throws IOException {
        String code = "";
        String message = "";
        UserAccount account = userAccountService.selectUserAccountByUserId(userId);
/*		Map<String,Object> mappara=new HashMap<String,Object>();
		mappara.put("userId",userId);
		mappara.put("currencyId",currencyId);
		CurrencyRecord currencyRecord=currencyRecordService.selectCurrencyRecordByPara(mappara);*/

        MerchantOrder order = merchantOrderService.selectMerchantOrderById(orderId);
        int status = order.getStatus();
        if (status == 0) {//支付中
            if (account != null) {
                int usercurr = account.getCurrency();//用户积分余额
                int currency = order.getCurrencyPayable();//积分
                if (usercurr >= currency) {
                    int resutl = usercurr - currency;//剩余积分
                    UserAccount userAccount = new UserAccount();
                    userAccount.setUserId(userId);
                    userAccount.setCurrency(resutl);
                    int resulta = userAccountService.updateUserAccount(userAccount);
                    if (resulta == 1) {
                        MerchantOrder merchantOrder = new MerchantOrder();
                        merchantOrder.setOrderId(orderId);
                        merchantOrder.setConfirmTime(new Date());
                        merchantOrder.setStatus(1);
                        merchantOrderService.updateMerchantOrder(merchantOrder);
                        CurrencyRecord currencyRecord = new CurrencyRecord();
                        currencyRecord.setBillId(orderId);
                        currencyRecord.setStatus("1");
                        currencyRecordService.updateCurrencyRecord(currencyRecord);
//                        code = ReturnMsg.paySuccess.getCode();
//                        message = ReturnMsg.paySuccess.getMessage();
                    } else {
                        code = "500";
                        message = "支付失败";
                    }
                } else {
                    code = "300";
                    message = "积分不足";
                }
            } else {
                code = "300";
                message = "用户不存在";
            }
        }
        writeJSON(null, response, code, message);
    }

    /**
     * 用勋章币购买课程资源流水
     */
    @ApiOperation("用勋章币购买课程资源流水")
    @GetMapping("/payByUserIdRecourd")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "userId", value = "用户ID", dataType = "string"),
            @ApiImplicitParam(name = "jrResourcesId", value = "视频资源id", dataType = "string"),
            @ApiImplicitParam(name = "freeFlagType", value = "付款类型", dataType = "string")})
    @ResponseBody
    public void payByUserIdRecourd(HttpServletResponse response, String userId, String jrResourcesId, String freeFlagType) throws IOException {
        String code = "";
        String message = "";
        String currencyId = "";
        UserAccount account = userAccountService.selectUserAccountByUserId(userId);
        if (account != null) {
            int usercurr = account.getCurrency();//用户积分余额
            Resources resource = resourcesService.selectResourcesById(jrResourcesId);
            BigDecimal amount = resource.getAmount();//金额
            int currency = resource.getCurrency();//积分
            if ("2".equals(freeFlagType)) {//1 现金 2 勋章币
                if (usercurr >= currency) {
                    int resutl = usercurr - currency;//剩余积分
                    CurrencyRecord rencyRecord = new CurrencyRecord();
                    currencyId = UUIDUtils.getByUUId();
                    rencyRecord.setCurrencyId(currencyId);
                    rencyRecord.setCreateTime(new Date());
                    rencyRecord.setStatus("2");
                    rencyRecord.setUserId(userId);
                    rencyRecord.setBillId(currencyId);
                    rencyRecord.setCurrency(new BigDecimal(currency));
                    int res = currencyRecordService.insertCurrencyRecord(rencyRecord);
                    MerchantOrder merchantOrder = new MerchantOrder();
                    merchantOrder.setOrderId(currencyId);
                    merchantOrder.setCreateTime(new Date());
                    merchantOrder.setBillId(jrResourcesId);
                    merchantOrder.setCurrencyPayable(currency);
                    merchantOrder.setPayCurrency(currency);
                    merchantOrder.setUserId(userId);
                    merchantOrder.setType("2");
                    int res2 = merchantOrderService.insertMerchantOrder(merchantOrder);
                    if (res == 1 && res2 == 1) {
                        code = "200";
                        message = "下单成功";
                    }
                } else {
                    code = "300";
                    message = "积分不足";
                }
            } else if ("1".equals(freeFlagType)) {//现金支付

            }
        } else {
            code = "300";
            message = "用户不存在";
        }
        writeJSON(currencyId, response, code, message);
    }


    /**
     * 查询素材课件信息
     */
    @ApiOperation("查询素材课件信息")
    @GetMapping("/type")
    @ApiImplicitParams(
            {@ApiImplicitParam(name = "catalogId", value = "章节编号", dataType = "Integer"),
                    @ApiImplicitParam(name = "type", value = "素材类型", dataType = "String")})
    @ResponseBody
    public void selectByType(HttpServletResponse response, String catalogId, String type, Integer pageNo) throws IOException {
        int pageSize = 10;
        PageHelper.startPage(pageNo, pageSize);
        Map<String, Object> map = new HashMap<>();
        map.put("rCatalogid", catalogId);
        map.put("type", type);
        log.info(LogUtil.LogInfo("查询素材课件信息", new Date()));
        List<Resources> list = resourcesService.selectInfoByType(map);
        PageInfo<Resources> page = new PageInfo<>(list);
        writeJSON(page, response, "200", "success");
    }
}
